package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.properties.BaiduMapProperties;
import com.sky.result.Result;
import com.sky.utils.HttpClientUtil;
import com.sky.webSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import io.netty.handler.codec.MessageAggregationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    //百度地图 地理编码 api
    private static final String BAIDU_GEOCODING = "https://api.map.baidu.com/geocoding/v3";
    //百度地图 路线规划 api (求两地之间距离)
    private static final String BAIDU_ROUTE = "https://api.map.baidu.com/directionlite/v1/driving";

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduMapProperties baiduMapProperties;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional  // 开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //先进行判断 业务是否合法（地址簿是否正常  购物车数据是否正常）
        AddressBook addressBook= addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //判断地址簿与商家地址的距离   需要调用到百度的api
        //在外面 写一个函数来进行判断
        boolean flag = judgeDistance(addressBook);
        if (!flag) {
            throw new AddressBookBusinessException(MessageConstant.GET_DISTANCE_FAILED);
        }
        //获取购物车数据  来判断购物车数据是否正常
        ShoppingCart shoppingCart =new ShoppingCart();
        shoppingCart.setId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new MessageAggregationException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1.向订单表插入1条数据
        // 对订单表需要的值进行赋值
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());//对订单信息赋值
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));  //订单号 用时间组成
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orderMapper.insert(orders);
        //2.向订单明细表插入n条数据
        List<OrderDetail> ordersList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail(); //订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            ordersList.add(orderDetail);
        }
        orderDetailMapper.insertBath(ordersList);
        //3.清空购物车
        shoppingCartMapper.delete(shoppingCart);
        //4.返回封装VO
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }




    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        } //不使用微信支付 直接重定向

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        ////不使用微信支付 直接重定向
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单

        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();

        //获取订单号码
        String orderNumber = ordersPaymentDTO.getOrderNumber();

        log.info("调用updateStatus，用于替换微信支付更新数据库状态的问题");
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderNumber);

        //不使用微信支付 直接重定向
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //使用websocket推送消息给 管理端
        //先使用  map 对 需要推送的消息进行装配
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        //再将其 转换成 json
        String json = JSON.toJSONString(map);
        //再使用  websocketServer 发送消息
        webSocketServer.sendToAllClient(json);
        log.info("推送 新的订单 给管理端，订单号：" + outTradeNo);
        orderMapper.update(orders);
    }

    /**
     * 订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        log.info("分页查询，参数：{}", ordersPageQueryDTO);
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        for (Orders orders :page) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
            orders.setOrderDetailList(orderDetailList);
        }
        Page<Orders> pagelist=(Page<Orders>) page;
        return new PageResult(pagelist.getTotal(), pagelist.getResult());
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Orders show(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setOrderDetailList(orderDetailMapper.getByOrderId(id));
        return orders;
    }


    /**
     * 用户取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.cancel(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getById(id);
        orders.setOrderDetailList(orderDetailMapper.getByOrderId(id));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setCheckoutTime(null);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.insert(orders);
        long Orderid=orders.getId();
        List<OrderDetail> orderDetailList = orders.getOrderDetailList();
        for (OrderDetail od : orderDetailList) {
            od.setOrderId(Orderid);
        }
        orderDetailMapper.insertBath(orders.getOrderDetailList());
    }

    /**
     * 订单统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.countStatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .deliveryStatus(Orders.CONFIRMED)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }



    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = new Orders().builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .deliveryStatus(Orders.DELIVERY_IN_PROGRESS)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = new Orders().builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryStatus(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 订单催单
     *
     * @param id
     */
    @Override
    public void remind(Long id) {
        // 根据订单查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type", 2);  //1：通知，2：催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        String json = JSON.toJSONString(map);
        log.info("推送 催单 给客户端，内容：{}", json);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 判断当前地址簿的经纬度是否在配送范围
     *
     * @param addressBook
     * @return
     *
     *
     */
    private boolean judgeDistance(AddressBook addressBook) {
        Map map = new HashMap();
        map.put("address", baiduMapProperties.getShopAddress());
        map.put("output","json");
        map.put("ak",baiduMapProperties.getAk());

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet(BAIDU_GEOCODING, map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        log.info("店铺经纬度坐标：{}",shopLngLat);



        //获取用户收货地址经纬度坐标
        map.put("address",addressBook.getCityName() + addressBook.getDistrictName()+addressBook.getDetail());
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet(BAIDU_GEOCODING, map);
        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }
        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;
        log.info("用户收货地址经纬度坐标：{}",userLngLat);

        //获取配送路线
        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");



        //路线规划
        String json = HttpClientUtil.doGet(BAIDU_ROUTE, map);
        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }
        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        log.info("配送距离：{}",distance);
        return distance < 5000;
    }
}


